/*
 * Timer.cpp
 *
 *  Created on: 04.05.2011
 *      Author: Hugme
 */

#include "Timer.h"
/*
 *  setupPulseAndTimer
 *
 *  This routine is responsible for setting up a pulse so it
 *  sends a message with code MT_TIMER.  It then sets up a
 *  periodic timer that fires once per second.
 */

int Timer::restartTimer(int timerID) {
	int returnValue;
	returnValue = timer_delete(timerID);
	if (returnValue == 0) {
		Timer::addTimer(chid, sec, nsec, intervallSec, intervallNsec);
	}
	return returnValue;
}

struct itimerspec* Timer::abortTimer(int timerID) {
	itimerspec* rTime = Timer::getRemainingTime(timerID);
	if (timer_delete(timerID) != 0) {
		fprintf(stderr, "couldn't stop timer!\n");
		perror(NULL);
		exit(EXIT_FAILURE);
	}
	return rTime;
}

struct itimerspec* Timer::pauseTimer(int timerID) {
	return Timer::abortTimer(timerID);
}

int Timer::getTimerID() {
	return Timer::timerid;
}

int Timer::resumeTimer(struct itimerspec* time) {
	Timer::addTimer(Timer::chid, time->it_value.tv_sec, time->it_value.tv_nsec,
			time->it_interval.tv_sec, time->it_interval.tv_nsec);
	return Timer::chid;
}

struct itimerspec* Timer::getRemainingTime(int timerID) {
	if (timer_gettime(timerID, &remainingTime) != 0) {
		fprintf(stderr, "couldn't get remaining time!\n");
		perror(NULL);
		exit(EXIT_FAILURE);
	}
	return &remainingTime;
}

void Timer::addTimer(int chid, int sec, int nsec, int intervallSec,
		int intervallNsec) {
	Timer::chid = chid;
	Timer::sec = sec;
	Timer::nsec = nsec;
	Timer::intervallSec = intervallSec;
	Timer::intervallNsec = intervallNsec;

	// create a connection back to ourselves
	Timer::coid = ConnectAttach(0, 0, chid, 0, 0);
	if (Timer::coid == -1) {
		fprintf(stderr, "couldn't ConnectAttach to self!\n");
		perror(NULL);
		exit(EXIT_FAILURE);
	}

	// set up the kind of event that we want to deliver -- a pulse
	SIGEV_PULSE_INIT (&event, Timer::coid, SIGEV_PULSE_PRIO_INHERIT, CODE_TIMER, 0);

	// create the timer, binding it to the event
	if (timer_create(CLOCK_REALTIME, &event, &timerid) == -1) {
		fprintf(stderr, "couldn't create a timer, errno %d\n", errno);
		perror(NULL);
		exit(EXIT_FAILURE);
	}

	// setup the timer
	timer.it_value.tv_sec = sec;
	timer.it_value.tv_nsec = nsec;
	timer.it_interval.tv_sec = intervallSec;
	timer.it_interval.tv_nsec = intervallNsec;

	// and start it!
	timer_settime(timerid, 0, &timer, NULL);
}
